import requests
import json
import re
from get_artcle_statistics import *
from tqdm import tqdm


def article_list_all():
    id_list = []
    name_list = []

    url = "https://baijiahao.baidu.com/builderinner/open/resource/query/articleListall"

    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36",
    }

    data = {
        "app_id": "1689933945625238",
        "app_token": "84b4ca975911e2fcd36d9609dac0cda6",
        "page_size": 20,  # 查询页码
        "page_no": 1,  # 查询条数
        "article_type": "video",
        "end_time": "",
        "collection": "publish",
    }

    response = requests.post(url=url, data=data, headers=headers)

    id_list0 = response.text
    print(id_list0)
    items = re.findall(r'"items":(.+)},"errno":0,"errmsg":"\\u6210\\u529f"}', id_list0)
    info = eval(str(items))
    dict1 = eval(info[0])

    for key, value in dict1.items():
        name_list.append(value["title"])
        id_list.append(value["article_id"])

    return id_list, name_list


def get_video_info_all(id_list, name_list):
    info = []

    info = {name_list[i]: get_article_statistics(id_list[i]) for i in range(len(id_list))}

    for key, value in info.items():
        print(f"{key}\n{value}\n")

    """
    for i in range(len(id_list)):
        info.append(name_list[i])
        print(info)
        info.append(get_article_statistics(id_list[i]))
        
    print(info)
    """
    return info


def save(id_list):
    fp = open("./article_list.json", "w", encoding="utf8")
    json.dump(info, fp=fp, ensure_ascii=False, indent=True)


if __name__ == "__main__":
    id_list, name_list = article_list_all()
    info = get_video_info_all(id_list, name_list)
    save(info)
